package com.example.sunmiv1.adapter;

import android.content.Context;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.DigitsKeyListener;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.entity.DepositGoodsInfo;
import com.example.sunmiv1.entity.GoodsStoreRetreatInfo;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.ACache;

import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class DepositGoodsAdapter extends RecyclerView.Adapter<DepositGoodsAdapter.prcgVholder> {
    private DepositGoodsAdapter.CheckBoxListener mCheckBoxListener;
    private String pricePermission;// 門店查看價格權限
    private Context context;
    private ACache aCache;
    private List<DepositGoodsInfo.DataBean.ListBean> list;
    private int type;//1 AddDepositActivity  出庫單添加,2 PurchaseOrderAddActivity採購單添加

    public DepositGoodsAdapter(Context context, List<DepositGoodsInfo.DataBean.ListBean> list, int type) {
        this.context = context;
        this.list = list;
        this.type = type;
        aCache = ACache.get(context);
        pricePermission = aCache.getAsString("showPrice");
    }

    @Override
    public DepositGoodsAdapter.prcgVholder onCreateViewHolder(ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.deposit_goods_adapter, parent, false);
        return new DepositGoodsAdapter.prcgVholder(view);
    }

    @Override
    public void onBindViewHolder(DepositGoodsAdapter.prcgVholder viewHolder, int position) {
        viewHolder.depositGoodsCheck.setOnCheckedChangeListener(null);
        viewHolder.depositGoodsCheck.setChecked(list.get(position).isChecked());
        viewHolder.depositGoodsCheck.setOnCheckedChangeListener((buttonView, isChecked) -> {
            list.get(position).setChecked(isChecked);
            notifyDataSetChanged();
        });
        viewHolder.depositGoodsName.setText(list.get(position).getGoods_name());
        viewHolder.depositGoodsFreightNumber.setText(list.get(position).getGoods_number());
        viewHolder.depositGoodsCode.setText(list.get(position).getGoods_code());
        if (TextUtils.isEmpty(list.get(position).getSku_name())) {
            viewHolder.layoutSkuName.setVisibility(View.GONE);
        } else {
            viewHolder.layoutSkuName.setVisibility(View.VISIBLE);
            viewHolder.infoSkuName.setText(list.get(position).getSku_name());
        }
        if (type == 1) {
            viewHolder.depositGoodsTvStock.setText(R.string.stock);
            viewHolder.depositGoodsStock.setText(list.get(position).getGoods_num() + "");
            viewHolder.depositGoodsTvPrice.setText(R.string.ExWarehousePrice);
            viewHolder.depositGoodsPrice.setText(list.get(position).getCost_price() + "");
            viewHolder.layoutCostPrice.setVisibility(View.VISIBLE);
            viewHolder.infoCostPrice.setText(list.get(position).getCost_price() + "");
            viewHolder.depositGoodsTvNum.setText(R.string.AllocationQuantity);
            ((View) viewHolder.depositGoodsRetailPrice.getParent()).setVisibility(View.GONE);
            ((View) viewHolder.depositGoodsOnlinePrice.getParent()).setVisibility(View.GONE);
        } else {
            viewHolder.depositGoodsTvStock.setText(R.string.AvailableInventory);
            viewHolder.depositGoodsStock.setText(list.get(position).getGoods_num() + "");
            viewHolder.depositGoodsTvPrice.setText(R.string.PurchasePrice);
            viewHolder.layoutCostPrice.setVisibility(View.GONE);
            viewHolder.depositGoodsPrice.setText(list.get(position).getPurchase_price() + "");
            viewHolder.depositGoodsTvNum.setText(R.string.PurchaseQuantity);
            if ("2".equals(aCache.getAsString("modify_price_state"))) {
                ((View) viewHolder.depositGoodsRetailPrice.getParent()).setVisibility(View.VISIBLE);
                ((View) viewHolder.depositGoodsOnlinePrice.getParent()).setVisibility(View.VISIBLE);
            } else {
                ((View) viewHolder.depositGoodsRetailPrice.getParent()).setVisibility(View.GONE);
                ((View) viewHolder.depositGoodsOnlinePrice.getParent()).setVisibility(View.GONE);
            }
            viewHolder.depositGoodsRetailPrice.setText(list.get(position).getRetail_price());
            viewHolder.depositGoodsOnlinePrice.setText(list.get(position).getOnline_price());
        }
        if ("2".equals(list.get(position).getPricing_method())) {//稱重商品
            viewHolder.depositGoodsNum.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        } else {
            viewHolder.depositGoodsNum.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
        }
//        viewHolder.infoUnit.setText(list.get(position).getCompany());
        Tools.hideViewInItem(list.get(position).getCompany(), viewHolder.infoUnit);
        if (type == 1) {
            viewHolder.depositGoodsNum.setText(list.get(position).getOutput_num());
        } else {
            viewHolder.depositGoodsNum.setText(list.get(position).getPurchase_num());
        }

        if ("1".equals(list.get(position).getSerial_number_state())) {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.VISIBLE);
            viewHolder.depositGoodsNum.setVisibility(View.GONE);
            if (type == 1) {
                if (TextUtils.isEmpty(list.get(position).getOutput_num())) {
                    viewHolder.inventorySearchAdapterInventoryTv.setText("0");
                } else {
                    viewHolder.inventorySearchAdapterInventoryTv.setText(list.get(position).getOutput_num());
                }
            } else {
                if (TextUtils.isEmpty(list.get(position).getPurchase_num())) {
                    viewHolder.inventorySearchAdapterInventoryTv.setText("0");
                } else {
                    viewHolder.inventorySearchAdapterInventoryTv.setText(list.get(position).getPurchase_num());
                }
            }
        } else {
            viewHolder.inventorySearchAdapterChooseSerial.setVisibility(View.GONE);
            viewHolder.depositGoodsNum.setVisibility(View.VISIBLE);
        }


        final TextWatcher dgnTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                limitDecimal(charSequence, viewHolder.depositGoodsNum);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.depositGoodsNum.hasFocus()) {
                    if (type == 1) {
                        list.get(position).setOutput_num(s.toString().trim());
                    } else {
                        list.get(position).setPurchase_num(s.toString().trim());
                    }
                }
                if (viewHolder.depositGoodsQualityGuaranteePeriod.hasFocus()) {
                    list.get(position).setQuality_guarantee_period(s.toString().trim());
                }
                if (viewHolder.depositGoodsRetailPrice.hasFocus()) {
                    list.get(position).setRetail_price(s.toString().trim());
                }
                if (viewHolder.depositGoodsOnlinePrice.hasFocus()) {
                    list.get(position).setOnline_price(s.toString().trim());
                }
            }
        };
        setETFocusChangeListener(position, dgnTextWatcher, viewHolder.depositGoodsNum);

        setETFocusChangeListener(position, dgnTextWatcher, viewHolder.depositGoodsQualityGuaranteePeriod);

        setETFocusChangeListener(position, dgnTextWatcher, viewHolder.depositGoodsRetailPrice);
        setETFocusChangeListener(position, dgnTextWatcher, viewHolder.depositGoodsOnlinePrice);

        final TextWatcher dgpTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                limitDecimal(charSequence, viewHolder.depositGoodsPrice);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.depositGoodsPrice.hasFocus()) {
                    if (type == 1) {
                        if (!TextUtils.isEmpty(s.toString().trim())) {
                            list.get(position).setCost_price(Double.parseDouble(s.toString().trim()));
                        } else {
                            list.get(position).setCost_price(0);
                        }
                    } else {
                        if (!TextUtils.isEmpty(s.toString().trim())) {
                            list.get(position).setPurchase_price(s.toString().trim());
                        } else {
                            list.get(position).setPurchase_price("0");
                        }
                    }
                }

            }
        };
        setETFocusChangeListener(position, dgpTextWatcher, viewHolder.depositGoodsPrice);


        viewHolder.depositGoodsRemark.setText(list.get(position).getRemark());
        final TextWatcher dgrTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (viewHolder.depositGoodsRemark.hasFocus()) {
                    list.get(position).setRemark(s.toString().trim());
                }

            }
        };
        setETFocusChangeListener(position, dgrTextWatcher, viewHolder.depositGoodsRemark);

        if ("2".equals(pricePermission)) {
            viewHolder.layoutCostPrice.setVisibility(View.GONE);
            ((View) viewHolder.depositGoodsPrice.getParent()).setVisibility(View.GONE);
        }
        final TextView buildDate = viewHolder.depositGoodsBuildDate;
        final int index = position;
        buildDate.setOnClickListener(v -> {
            Tools.getDateFromDatePickerDialog(buildDate, time -> list.get(index).setBuild_date(time));
        });
        viewHolder.inventorySearchAdapterChoose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choose.choose(position);
            }
        });
    }

    private Choose choose;

    public void setChoose(Choose choose) {
        this.choose = choose;
    }

    public interface Choose {
        void choose(int index);
    }

    @Override
    public int getItemCount() {
        return list == null ? 0 : list.size();
    }

    static class prcgVholder extends RecyclerView.ViewHolder {
        @BindView(R.id.depositGoods_check)
        CheckBox depositGoodsCheck;
        @BindView(R.id.depositGoods_name)
        TextView depositGoodsName;
        @BindView(R.id.info_sku_name)
        TextView infoSkuName;
        @BindView(R.id.layout_sku_name)
        RelativeLayout layoutSkuName;
        @BindView(R.id.depositGoods_freightNumber)
        TextView depositGoodsFreightNumber;
        @BindView(R.id.depositGoods_code)
        TextView depositGoodsCode;
        @BindView(R.id.info_unit)
        TextView infoUnit;
        @BindView(R.id.depositGoods_tvStock)
        TextView depositGoodsTvStock;
        @BindView(R.id.depositGoods_stock)
        TextView depositGoodsStock;
        @BindView(R.id.info_cost_price)
        TextView infoCostPrice;
        @BindView(R.id.layout_cost_price)
        RelativeLayout layoutCostPrice;
        @BindView(R.id.depositGoods_tvPrice)
        TextView depositGoodsTvPrice;
        @BindView(R.id.depositGoods_price)
        EditText depositGoodsPrice;
        @BindView(R.id.depositGoods_tvNum)
        TextView depositGoodsTvNum;
        @BindView(R.id.depositGoods_num)
        EditText depositGoodsNum;
        @BindView(R.id.depositGoods_remark)
        EditText depositGoodsRemark;
        @BindView(R.id.depositGoods_quality_guarantee_period)
        EditText depositGoodsQualityGuaranteePeriod;
        @BindView(R.id.depositGoods_build_date)
        TextView depositGoodsBuildDate;
        @BindView(R.id.depositGoods_retailPrice)
        EditText depositGoodsRetailPrice;
        @BindView(R.id.depositGoods_onlinePrice)
        EditText depositGoodsOnlinePrice;
        @BindView(R.id.inventorySearch_adapter_chooseSerial)
        LinearLayout inventorySearchAdapterChooseSerial;
        @BindView(R.id.inventorySearch_adapter_choose)
        TextView inventorySearchAdapterChoose;
        @BindView(R.id.inventorySearch_adapter_inventoryTv)
        TextView inventorySearchAdapterInventoryTv;

        public prcgVholder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    // 全選
    public void checkAll() {
        Iterator<DepositGoodsInfo.DataBean.ListBean> iterable = list.iterator();
        while (iterable.hasNext()) {
            iterable.next().setChecked(true);
        }
        notifyDataSetChanged();
    }

    // 全不選
    public void checkAllNot() {
        Iterator<DepositGoodsInfo.DataBean.ListBean> iterable = list.iterator();
        while (iterable.hasNext()) {
            iterable.next().setChecked(false);
        }
        notifyDataSetChanged();
    }

    // 移除一個
    public void removeOne(int position) {
        list.remove(position);
    }

    /* 移除多個 */
    public void removeMore(SparseArray<Integer> positions) {
//        list.r
    }


    public static interface CheckBoxListener {
        void setCheckBoxListener(boolean isChecked, int position);
    }

    public void setCBListener(DepositGoodsAdapter.CheckBoxListener cbListener) {
        this.mCheckBoxListener = cbListener;
    }

    /**
     * 限制小數點後三位
     *
     * @param charSequence str
     * @param et           et
     */
    private void limitDecimal(CharSequence charSequence, EditText et) {
        LogUtil.i("onTextChanged: charSequence=" + charSequence.toString());
        if (charSequence.toString().contains(".")) {
            if (-1 != charSequence.toString().indexOf(".", charSequence.toString().indexOf(".") + 1)) {
                et.setText(charSequence.toString().
                        substring(0, charSequence.toString().length() - 1));
                et.setSelection(charSequence.length() - 1);
            } else {
                if (charSequence.length() - 1 - charSequence.toString().indexOf(".") > 3) {
                    charSequence = charSequence.toString().subSequence(0, charSequence.toString().indexOf(".") + 4);
                    et.setText(charSequence);
                    et.setSelection(charSequence.length());
                }
            }
        }
        if (charSequence.toString().trim().substring(0).equals(".")) {
            charSequence = "0" + charSequence;
            et.setText(charSequence);
            et.setSelection(2);
        }

        if (charSequence.toString().startsWith("0") && charSequence.toString().trim().length() > 1) {
            if (!charSequence.toString().substring(1, 2).equals(".")) {
                et.setText(charSequence.subSequence(1, 2));
                et.setSelection(1);
            }
        }
    }

    /**
     * 設置edittext焦點的監聽器
     *
     * @param position    pos
     * @param textWatcher watcher
     * @param editText    et
     */
    private void setETFocusChangeListener(int position, TextWatcher textWatcher, EditText editText) {
        editText.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                ((EditText) v).addTextChangedListener(textWatcher);
                Log.e("addTextChanged", position + "");
            } else {
                ((EditText) v).removeTextChangedListener(textWatcher);
                Log.e("removeTextChanged", position + "");
            }
        });
    }
}
